#include "gamelogic.h"
#include "utils.h"
#include "log.h"

#include <Windows.h>
#include <QApplication>
#include <QtDebug>
#include <DbgHelp.h>

LONG ApplicationCrashHandler(_EXCEPTION_POINTERS *pException)
{
    // 创建Dump文件
    HANDLE hDumpFile = CreateFile(L"crash.dmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hDumpFile != INVALID_HANDLE_VALUE)
    {
        //Dump信息
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pException;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = TRUE;

        //写入Dump文件内容
        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
    }

    //这里弹出一个错误对话框并退出程序
    QMessageBox msgbox(QMessageBox::Icon::Critical, UIUtils::winTitle(WIN_TITLE_ERROR), MSG_CRASH);
    msgbox.exec();

    return EXCEPTION_EXECUTE_HANDLER;
}

int main(int argc, char *argv[])
{
    QList<QString> argList;
    std::map<QString, QString> argMap;
    for(int i = 1; i < argc; i++)
    {
        QString strArg = QString(argv[i]);
        argList.append(strArg);
        int idx = strArg.indexOf('=');
        if(idx >= 0)
        {
            QString argName = strArg.left(idx);
            QString argValue = strArg.right(strArg.length() - idx - 1);
            argMap[argName] = argValue;
        }
        else
        {
            argMap[strArg] = 'Y';
        }
    }

    QApplication a(argc, argv);
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);

#ifdef QT_NO_DEBUG
    auto logFile = PathUtils::resource(RES_LOGFILE);
    if(QFile::exists(logFile))
    {
        QFile::remove(PathUtils::resource(RES_PREVLOGFILE));
        QFile::rename(logFile, PathUtils::resource(RES_PREVLOGFILE));
    }
    logSysInit(logFile);
#endif

    qInfo() << "启动参数：" << argList.join(", ");

    GameLogic game;
    game.setUp(&a, argList, std::make_unique<std::map<QString, QString>>(argMap));

    auto ret = a.exec();
    if(EXITCODE_REBOOT == ret)
    {
        QProcess::startDetached(QCoreApplication::applicationFilePath(), argList);
    }
    return ret;
}
